package com.ebt.m.msgnote.presenter;

import android.content.Context;

import com.ebt.m.AppInitService;
import com.ebt.m.commons.buscomponent.listview.BaseListContract;
import com.ebt.m.commons.buscomponent.listview.BaseListPresenter;
import com.ebt.m.commons.buscomponent.listview.RecyclerFootManger;
import com.ebt.m.commons.buscomponent.listview.SectionItem;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.commons.model.data.Constants;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.data.rxModel.api.MsgAPI;
import com.ebt.m.msgnote.bean.TypeMsgItems;
import com.ebt.m.utils.ConfigData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

import static com.ebt.m.msgnote.MsgConstant.MSG_DATE_VIEW_TYPE;
import static com.ebt.m.msgnote.MsgConstant.MSG_TYPE_VIEW_TYPE;

/**
 * @author allen
 * Created by allen on 2018/7/27 11:09.
 */
public class TypeMsgListPresenter extends BaseListPresenter<BaseListContract.IView> {
    private int currentPage = 1;
    private int pageSize = 10;
    int type = 0;
    Set<String> headers = new HashSet<>();

    public TypeMsgListPresenter(Context context, BaseListContract.IView iView) {
        super(context, iView);
    }

    @Override
    public void loadNew(Object... args) {
        if (args != null && args.length > 0) {
            type = (int) args[0];
        }
        refreshList(true, type);
    }

    private void refreshList(boolean isLoadNew, int args) {
        if (isLoadNew) {
            currentPage = 1;
            headers.clear();
        }
        Map<String, String> params = new HashMap<>();
        params.put("type", args + "");
        params.put("page", currentPage + "");
        params.put("pageSize", ConfigData.PAGE_COUNT_LIMIT + "");
        iView.showProgress(true);
        MsgAPI opportunityApi = AppInitService.getMsgApi();
        opportunityApi.getTypeMsgList(params)
                .filter(settingFootviewStatus(isLoadNew))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    iView.updateData(createSectionItem(response.getData()));
                }, throwable -> {
                    throwable.printStackTrace();
                    iView.errorData();
                });
    }

    @Override
    public void refresh() {
        loadNew();
    }

    @Override
    public void loadNext(Object... args) {
        Map<String, String> params = new HashMap<>();
        params.put("type", type + "");
        params.put("page", currentPage + 1 + "");
        params.put("pageSize", ConfigData.PAGE_COUNT_LIMIT + "");
        MsgAPI opportunityApi = AppInitService.getMsgApi();
        opportunityApi.getTypeMsgList(params)
                .filter(settingFootviewStatus(true))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    currentPage++;
                    iView.updateDataAdd(createSectionItem(response.getData()));
                }, throwable -> {
                    throwable.printStackTrace();
                    iView.setFootStatus(RecyclerFootManger.STATUS_ERROR, true);
                });
    }

    /**
     * change the footview status according to count of  fetching data
     *
     * @param isLoadNew
     * @param <T>
     * @return
     */
    protected <T> Predicate<BaseDataResult<List<T>>> settingFootviewStatus(final boolean isLoadNew) {
        return listBaseDataResult -> {
            List<TypeMsgItems.TypeMsg> items = new ArrayList<>();
            List<TypeMsgItems> k = (List<TypeMsgItems>) listBaseDataResult.getData();
            for (int i = 0; i < k.size(); i++) {
                items.addAll(k.get(i).getItems());
            }

            if (listBaseDataResult == null || items.size() == 0) {
                if (!isLoadNew) {
                    iView.setFootStatus(RecyclerFootManger.STATUS_END, true);
                    return false;
                } else {
                    iView.setFootStatus(RecyclerFootManger.STATUS_NORMAL, true);
                    return true;
                }
            }

            if (items.size() < Constants.PAGE_COUNT_LIMIT) {
                iView.setFootStatus(RecyclerFootManger.STATUS_END, true);
                return true;
            } else {
                iView.setFootStatus(RecyclerFootManger.STATUS_LOADING, true);
                return true;
            }
        };
    }

    @Override
    public List<SectionItem> createSectionItem(List datas) {
        List<SectionItem> list = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            TypeMsgItems item = (TypeMsgItems) datas.get(i);
            if (!headers.contains(item.getDate())) {
                list.add(new SectionItem(MSG_DATE_VIEW_TYPE, item.getDate()));
                headers.add(item.getDate());
            }
            for (TypeMsgItems.TypeMsg bean : item.getItems()) {
                list.add(new SectionItem(MSG_TYPE_VIEW_TYPE, bean));
            }
        }
        return list;
    }

    public void readMsg(int msgId) {
        MsgAPI opportunityApi = AppInitService.getMsgApi();
        opportunityApi.readMsg(msgId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
//                    ReadMsgBean bean = response.getData();
                    Logger.i(msgId + " is readed");
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }

}
